package com.lzl.redisratelimit.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Component
public class RateLimiter {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private RedisScript<Long> redisScript;

    public boolean isLimit(String scene, String key, int bucketSize, int addSize, int addRate) {
        List<String> limitKey = LimitKey.getLimitKey(scene, key);
        Long token = stringRedisTemplate.execute(redisScript, limitKey, String.valueOf(bucketSize), String.valueOf(addSize), String.valueOf(addRate), String.valueOf(System.currentTimeMillis()));
        // 这里做了简单处理如果脚本执行错误，可以根据实际情况处理。
        return token == null || token < 0;
    }
}
